package com.service.aliyun.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.ObjectMetadata;
import com.service.aliyun.IOssService;
import com.utils.enums.ENUM_SUCESS;

@Service
@ConfigurationProperties(prefix="aliyun")
public class OssServiceImpl implements IOssService {

	static Logger logger = LoggerFactory.getLogger(OssServiceImpl.class);
	
	private String endpoint;
	
	private String accessKeyId;
	
	private String accessKeySecret;
	
	private String bucketName;
	
	private String cdnUrl;
	
	private OSSClient ossClient;

	@Override
	public Integer OSSUpload(String filekey, InputStream is) throws OSSException, ClientException, Exception{

		logger.info("OSS-Started");

		ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		try {
			if (ossClient.doesBucketExist(bucketName)) {
				logger.info("获取到bucket");
			} else {
				logger.error("bucket不存在");
				throw new OSSException("bucket不存在");
			}
			// 查看Bucket信息
			// BucketInfo info = ossClient.getBucketInfo(bucketName);
			// logger.info("Bucket " + bucketName + "的信息如下：");
			// logger.info("\t数据中心：" + info.getBucket().getLocation());
			// logger.info("\t创建时间：" + info.getBucket().getCreationDate());
			// logger.info("\t用户标志：" + info.getBucket().getOwner());
			ossClient.putObject(bucketName, filekey, is);
			logger.info("Object：" + filekey + "存入OSS成功。");
		} finally {
			ossClient.shutdown();
			IOUtils.safeClose(is);
		}
		logger.info("OSS-Completed");
		return ENUM_SUCESS.SUCESS.value;
	}
	
	@Override
	public Integer OSSUpload(String filekey, InputStream is,ObjectMetadata meta) throws OSSException, ClientException, Exception{

		logger.info("OSS-Started");

		ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		try {
			if (ossClient.doesBucketExist(bucketName)) {
				logger.info("获取到bucket");
			} else {
				logger.error("bucket不存在");
				throw new OSSException("bucket不存在");
			}
			// 查看Bucket信息
			// BucketInfo info = ossClient.getBucketInfo(bucketName);
			// logger.info("Bucket " + bucketName + "的信息如下：");
			// logger.info("\t数据中心：" + info.getBucket().getLocation());
			// logger.info("\t创建时间：" + info.getBucket().getCreationDate());
			// logger.info("\t用户标志：" + info.getBucket().getOwner());
			ossClient.putObject(bucketName, filekey, is, meta);
			logger.info("Object：" + filekey + "存入OSS成功。");
		} finally {
			ossClient.shutdown();
			IOUtils.safeClose(is);
		}
		logger.info("OSS-Completed");
		return ENUM_SUCESS.SUCESS.value;
	}

	@Override
	public Integer OSSDelete(String filekey)  throws OSSException, ClientException, Exception{
		ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		try {
			ossClient.deleteObject(bucketName, filekey);
		} finally {
			ossClient.shutdown();
		}
		return ENUM_SUCESS.SUCESS.value;
	}
	
	@Override
	public Map<String,String> fillOssAndCdnPath(String pakg, String fileName){
		Map<String,String> map = new HashMap<String, String>(); 
		map.put("cdnUrl", cdnUrl + pakg + fileName);
		map.put("ossUrl", endpoint.replace("https://", "https://"+bucketName+".") + "/" + pakg + fileName);
		return map;
	}
	
	/**
	 * 上传文件夹到oss
	 * @param path
	 * @param ossPackage
	 * @throws OSSException
	 * @throws ClientException
	 * @throws Exception
	 */
	public static void updateJs(String path, String ossPackage) throws OSSException, ClientException, Exception{
		File file = new File(path);
		
		if (file.exists()) {
            File[] files = file.listFiles();
            if (files.length == 0) {
                System.out.println("文件夹是空的!");
                return;
            } else {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
                        System.out.println("文件夹:" + file2.getAbsolutePath());
                        updateJs(file2.getAbsolutePath(),ossPackage);
                    } else {
                        System.out.println("文件:" + file2.getAbsolutePath());
                        String pathoss = file2.getAbsolutePath();
                        pathoss = pathoss.replaceAll("\\\\", "\\/");
                        System.out.println("----------------"+pathoss);
                        InputStream in = new FileInputStream(file2);
                        OSSlocalUpload("plugin/"+pathoss,in);
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
		
	}
	public static Integer OSSlocalUpload(String filekey, InputStream is) throws OSSException, ClientException, Exception{

		OSSClient client = new OSSClient("https://oss-cn-hangzhou.aliyuncs.com", "LTAI0xIu91M19vQ4", "KoeascKe1o4GdzinUB0pXqjwAX5oBk");
		try {
			if (client.doesBucketExist("bonebutterfly")) {
				System.out.println("获取到bucket");
			} else {
				System.out.println("bucket不存在");
				throw new OSSException("bucket不存在");
			}
			// 查看Bucket信息
			// BucketInfo info = ossClient.getBucketInfo(bucketName);
			// logger.info("Bucket " + bucketName + "的信息如下：");
			// logger.info("\t数据中心：" + info.getBucket().getLocation());
			// logger.info("\t创建时间：" + info.getBucket().getCreationDate());
			// logger.info("\t用户标志：" + info.getBucket().getOwner());
			client.putObject("bonebutterfly", filekey, is);
		} finally {
			client.shutdown();
			is.close();
		}
		return ENUM_SUCESS.SUCESS.value;
	}
	
	public static void main(String[] args) {
		try {
			updateJs("C:\\Users\\Administrator\\Desktop\\周报","plugin/");
		} catch (OSSException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getEndpoint() {
		return endpoint;
	}

	public void setEndpoint(String endpoint) {
		this.endpoint = endpoint;
	}

	public String getAccessKeyId() {
		return accessKeyId;
	}

	public void setAccessKeyId(String accessKeyId) {
		this.accessKeyId = accessKeyId;
	}

	public String getAccessKeySecret() {
		return accessKeySecret;
	}

	public void setAccessKeySecret(String accessKeySecret) {
		this.accessKeySecret = accessKeySecret;
	}

	public String getBucketName() {
		return bucketName;
	}

	public void setBucketName(String bucketName) {
		this.bucketName = bucketName;
	}

	public String getCdnUrl() {
		return cdnUrl;
	}

	public void setCdnUrl(String cdnUrl) {
		this.cdnUrl = cdnUrl;
	}

	public OSSClient getOssClient() {
		return ossClient;
	}

	public void setOssClient(OSSClient ossClient) {
		this.ossClient = ossClient;
	}
	
	
}
